<template>
	<div class="device-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="托盘码">
					<el-input v-model="state.queryParams.tray" placeholder="托盘码" clearable />
				</el-form-item>
				<el-form-item label="领料单号">
					<el-input v-model="state.queryParams.pickingNumber" placeholder="领料单号" clearable />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
					<el-button type="primary" icon="ele-Plus" @click="addWare">添加</el-button>
					<el-button type="danger" icon="ele-Warning" @click="batchDeleteEntrance">批量删除</el-button>
					<el-button type="primary" icon="ele-Download" @click="downloadTemplate">模版</el-button>
					<el-upload lass="upload-demo" :before-upload="beforeUpload" :http-request="handleUpload"
						:show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError">
						<el-button icon="ele-Upload">导入</el-button>
					</el-upload>
					<el-button type="primary" icon="ele-Download" @click="exportDate">导出</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.MateriaiData" style="width: 100%" v-loading="state.loading" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" prop="id" width="55" align="center" />
				<!-- <el-table-column type="index" label="序号" width="55" align="center" /> -->

				<el-table-column prop="serialNumber" label="序号" align="center" show-overflow-tooltip />
				<el-table-column prop="pickingNumber" label="领料单号" align="center" show-overflow-tooltip />
				<el-table-column prop="tray" label="托盘码" align="center" show-overflow-tooltip>
					<!-- <template #default="scope">
						<el-input v-model="scope.row.storey"  />
						{{ scope.row.storey }}
					</template> -->
				</el-table-column>
				<el-table-column prop="entranceandExit" label="出入口" align="center" show-overflow-tooltip>

				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />

				<el-table-column label="操作" width="140" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"
							@click="openEditWarehous(scope.row)"> 编辑 </el-button>
						<el-button size="small" text type="danger" @click="delWarehous(scope.row)"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" size="small" background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<EditEnteance ref="editEnteanceRef" :title="state.editWarehousTitle" @handleQuery="handleQuery" />
		<EditDevice ref="editDeviceRef" :title="state.editWarehousTitle" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="entrance">
import { onMounted, computed, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage, EmptyInstance } from 'element-plus';
import EditDevice from './component/editDevice.vue';
import { getAPI } from '/@/utils/axios-utils';


import { GetMateriaiPageListApi, DownloadMateriaiApi, MateriaiinportApi, MateriaiexportApi, BatchDeleteMateriaiApi } from '/@/api-services/apis/warehosue-materiai-api'; // 导入 API 服务
import { MateriailIssuanceInput, DeleteMateriailIssuance } from '/@/api-services/models/warehous-materiai-input'; // 导入获取实体
import { error } from 'console';
import { entries } from 'lodash-es';
import { downloadByData, getFileName } from '/@/utils/download';
import { deleteDataAPI } from '/@/api-dem-application/master/student-api';
import { BatchDeleteMaintenanceApi } from '/@/api-services/apis/warehouse-maintenance-api';


// ...其他导入

const editDeviceRef = ref<InstanceType<typeof EditDevice>>();
const state = reactive({
	loading: false,
	MateriaiData: [] as Array<MateriailIssuanceInput>,
	queryParams: {
		tray: undefined,
		pickingNumber: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
	editWarehousTitle: '',

});

onMounted(async () => {
	//console.log('当前路由参数:', route); // 添加路由参数调试
	handleQuery();

});

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	try {

		const res = await GetMateriaiPageListApi({
			...state.queryParams,
			page: state.tableParams.page,
			pageSize: state.tableParams.pageSize,
		});
		state.MateriaiData = res.data.result?.items || [];
		state.tableParams.total = res.data?.result?.total ?? 0;

	} catch {
		state.MateriaiData = [];
		state.tableParams.total = 0;
	}

	finally {
		state.loading = false;

	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.tray = undefined;
	state.queryParams.pickingNumber = undefined;
	handleQuery();
};

// 打开新增页面
const addWare = () => {
	const addData = {
		description: null,
		total: null,
		attachment: null,
		isenable: 1,
	};
	state.editWarehousTitle = '添加领料信息';
	editDeviceRef.value?.openDialog(addData);
};
// 假设存在一个方法可以获取选中行的数据，这里我们先定义一个 ref 来存储选中的行
const multipleSelection = ref<DeleteMateriailIssuance[]>([]);

const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
// 获取选中行的 idlist
const selectedIds = computed(() => multipleSelection.value.map(item => ({ id: item.id })));



const batchDeleteEntrance = async () => {

	try {
		if (selectedIds.value.length === 0) {
			ElMessage.error('请选择要操作的记录');
			return;
		}

		const res = await BatchDeleteMateriaiApi(selectedIds.value);

		// 检查 res 是否存在，避免出现未定义错误
		if (res && res.status === 200) {
			ElMessage.success('操作成功');
			handleQuery();
		}
		else {
			ElMessage.error('操作失败');
		}
	} catch (error) {
		ElMessage.error('操作失败');
	}
};
// 关闭新增页面提示
const closeAddDialog = () => {
	editDeviceRef.value?.openDialog(false);
};


// 打开编辑页面
const openEditWarehous = (row: any) => {
	state.editWarehousTitle = '编辑领料信息';
	editDeviceRef.value?.openDialog(row);
};

// 删除操作
const delWarehous = (row: any) => {
	ElMessageBox.confirm(`确定删除领料：【${row.pickingNumber}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				// 为确保类型匹配，显式指定传入对象的类型
				interface ItemWithId { id: number; }
				const itemWithId: ItemWithId = { id: row.id };
				await BatchDeleteMateriaiApi([itemWithId]);
				handleQuery();
				ElMessage.success('删除成功');
			} catch (error) {
				// console.error('删除失败:', error);
				ElMessage.error('删除失败，请稍后重试');
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除');
		});
};

const exportDate = async () => {
	try {
		state.loading = true;
		// 通常导出文件时需要设置 responseType 为 'blob'，以正确处理二进制数据
		// 为了解决类型不匹配问题，将 responseType 单独传递
		const config = { responseType: 'blob' };
		var res = await MateriaiexportApi(state.queryParams);
		state.loading = false;
		var fileName = getFileName(res.headers);
		// 假设增加一些日志记录，方便调试
		console.log('准备开始下载文件，文件数据:', res.data, '文件名:', fileName);
		downloadByData(res.data as any, fileName);
		ElMessage.success('导出成功' + fileName);
	}
	catch (error) {
		state.loading = false;
		ElMessage.error('导出失败');
	}
}

// #region 导入
// 上传前校验
const beforeUpload = (file: File) => {
	const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
		file.type === 'application/vnd.ms-excel'
	if (!isExcel) {
		ElMessage.error('只能上传 Excel 文件!')
		return false
	}
	return true
}
// 自定义上传方法
const handleUpload = async (options: any) => {
	const formData = new FormData()
	formData.append('file', options.file)
	// 这里调用你的上传API
	console.log('handleUpload', formData);
	try {
		const response = await MateriaiinportApi(formData).then((response) => {
			console.log('response', response);
			handleUploadSuccess(response);

		})
	} catch (error) {
		console.log('error', error);
		handleUploadError(error);
	}
}

// 上传成功回调
const handleUploadSuccess = (response: any) => {
	if (response.status === 200) {
		ElMessage.success('导入成功')
		handleQuery() // 刷新表格数据
	}
	else {
		ElMessage.error('导入失败')
	}
}

// 上传失败回调
const handleUploadError = (error: any) => {
	ElMessage.error(error || '导入失败' + error)
}

//下载文件
const downloadTemplate = async () => {
	try {
		DownloadMateriaiApi().then((response) => {

			const blob = new Blob([response.data])
			const fileName = getFileName(response.headers);
			downloadByData(response.data as any, fileName);

			ElMessage.success(`下载成功${fileName}`);
		}); // 调用下载模板的API

	} catch (error) {
		ElMessage.error('下载失败');
	}
};

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};
</script>
